from flask import *
from bluePrints.forms import *
from werkzeug.datastructures import MultiDict
from exts import *
from models import *


tieziA = Blueprint('tiezi',__name__,url_prefix='/teizi')
# teizi入口测试
@tieziA.route('/',methods=['GET','POST'])
def tiezitest():
    return 'tieizi'


# 发送帖子
@tieziA.route('/PostTiezi',methods=['POST','GET'])
def PostTiezi():
    if request.method == 'POST':
        form = PostTieziForm(MultiDict(request.get_json()))
        print("PostTiezi:",form.data)
        if form.validate():
            title = form.title.data
            content = form.content.data
            user_id = form.user_id.data
            tiezi1 = Tiezi(title=title,content=content,user_id=user_id)
            db.session.add(tiezi1)
            db.session.commit()
            
            return jsonify({
                'code':200,
                'msg':'发送成功',
                'data': {
                    'title': title,
                    'content': content,
                    'user_id': user_id,
                    'create_time': str(tiezi1.create_time),
                    'reply_num':0,
                    'like_num':0
                }



            })
        else:
            errors = {field: error[0] for field, error in form.errors.items()}
            print('errors',errors)
            return jsonify({'code': 400, 'errors': errors}),400
            # tiezi = tiezi(title=title,content=content)

    else:
        return '发送帖子，PostTiezi'

# 获取帖子列表
@tieziA.route('/getTieziList/<int:page>',methods=['GET'])
def getTieziList(page):
    try:
        tiezi_list = Tiezi.getTieziList(page)
        print('tiezi_list',tiezi_list)
        if tiezi_list == []:
            return jsonify({
                "code": 500,
                "message": f"获取第{page}页帖子失败",
                "data": None
            })
        else:
            tiezi_list1=[]
            for i in range(len(tiezi_list)):
                json = {
                    "id": tiezi_list[i].id,
                    "title": tiezi_list[i].title,
                    "content": tiezi_list[i].content,
                    "user_id": tiezi_list[i].user_id,
                    "user_name": User.query.filter(User.id==tiezi_list[i].user_id).first().username,
                    'reply_num':len((Tiezi.query.get(tiezi_list[i].id)).replies),
                    "create_time": str(tiezi_list[i].create_time),
                    'like_num':tiezi_list[i].like_num
                }
                tiezi_list1.append(json)
            return jsonify({
                "code": 200,
                "message": f"获取第{page}页帖子成功",
                "data": tiezi_list1
            })
    except Exception as e:
        print('错误',e)
        return jsonify({
            "code": 500,
            "message": f"获取列表数据失败: {str(e)}",
            "data": None
        })
    

# 发送回复
@tieziA.route('/postTeiziReply',methods=['POST','GET'])
def postTeiziReply():
    if request.method == 'POST':
        try:
            form = PostReplyForm(MultiDict(request.get_json()))
            print("postTeiziReply:",form.data)
            if form.validate():
                post_id = form.post_id.data
                user_id = form.user_id.data
                content = form.content.data
                reply = Reply(content=content,user_id=user_id,post_id=post_id)
                db.session.add(reply)
                db.session.commit()
                return jsonify({
                    'code':200,
                    'msg':'回复成功',
                    'reply_id': reply.id
                })
            else:
                errors = {field: error[0] for field, error in form.errors.items()}
                print('errors',errors)
                return jsonify({'code': 400, 'errors': errors}),400
        except Exception as e:
            print('错误',e)
            return jsonify({
                "code": 500,
                "message": f"获取列表数据失败: {str(e)}",
                "data": None
            })
    else:
        return '发送回复，postTeiziReply'


# 获取帖子下的回复
@tieziA.route('/getTieziReplys/<int:post_id>/<int:page>', methods=['GET'])
def getTieziReplys(post_id, page):
    try:
        # 获取帖子
        post = Tiezi.query.get(post_id)
        if post is None:
            return jsonify({
                "code": 500,
                "message": f"id为{post_id}的帖子不存在",
                "data": None
            }), 404
        
        # 计算分页起始点
        replies_query = Reply.query.filter(Reply.post_id == post_id)
        count_replis = replies_query.count()  # 获取总回复数
        replies = Reply.getTieziReplys(post_id, page)
        if replies == []:
            return jsonify({
                "code": 200,
                "message": f"id为{post_id}的帖子没有回复",
                "data": None
            })
        # 构建回复列表
        replies_data = []
        for reply in replies:
            replies_data.append({
                'id': reply.id,
                'content': reply.content,
                'reply_time': reply.reply_time.strftime('%Y-%m-%d %H:%M:%S'),
                'user_id': reply.user_id,
                'like_num': reply.like_num,
                'user_name': User.query.filter(User.id == reply.user_id).first().username
            })

        return jsonify({
            'code': 200,
            'msg': f'成功获取帖子id为{post_id}的回复',
            'data': replies_data,
            'count_replis': count_replis,
        })
    except Exception as e:
        print('错误', e)
        return jsonify({
            "code": 500,
            "message": f"获取数据失败: {str(e)}",
            "data": None
        })

    
# 获取用户发布的帖子
@tieziA.route('/getUserPosts/<int:user_id>', methods=['GET'])
def getUserPosts(user_id):
    try:
        # 获取用户
        user = User.query.get(user_id)
        if user is None:
            return jsonify({
                "code": 404,
                "message": f"id为{user_id}的用户不存在",
                "data": None
            }), 404
        
        # 获取用户发布的所有帖子
        posts = Tiezi.query.filter_by(user_id=user_id).order_by(Tiezi.create_time.desc()).all()
        
        if not posts:
            return jsonify({
                "code": 200,
                "message": f"用户{user.username}没有发布过帖子",
                "data": []
            })
        
        # 构建帖子列表
        posts_data = []
        for post in posts:
            posts_data.append({
                'id': post.id,
                'title': post.title,
                'content': post.content,
                'create_time': post.create_time.strftime('%Y-%m-%d %H:%M:%S'),
                'like_num': post.like_num,
                'reply_num': Reply.query.filter_by(post_id=post.id).count()
            })

        return jsonify({
            'code': 200,
            'message': f'成功获取用户{user.username}的帖子',
            'data': posts_data
        })
    except Exception as e:
        print('错误', e)
        return jsonify({
            "code": 500,
            "message": f"获取用户帖子失败: {str(e)}",
            "data": None
        })


@tieziA.route('/getTieziDetail/<int:post_id>', methods=['GET'])
def getTieziDetail(post_id):
    try:
        post = Tiezi.query.get(post_id)
        if post is None:
            return jsonify({
                "code": 404,
                "message": "帖子不存在",
                "data": None
            })
        
        user = User.query.get(post.user_id)
        reply_count = Reply.query.filter_by(post_id=post_id).count()
        
        return jsonify({
            "code": 200,
            "message": "获取帖子详情成功",
            "data": {
                "id": post.id,
                "title": post.title,
                "content": post.content,
                "user_id": post.user_id,
                "user_name": user.username,
                "create_time": str(post.create_time),
                "like_num": post.like_num,
                "reply_num": reply_count
            }
        })
    except Exception as e:
        print('错误', e)
        return jsonify({
            "code": 500,
            "message": f"获取帖子详情失败: {str(e)}",
            "data": None
        })

@tieziA.route('/like',methods=['POST','GET'])
def like():
    if request.method == 'POST':
        try:
            like_json = request.get_json()
            print("like:",like_json)
            if like_json.get('post_id'):
                form = PostLikeTieziForm(MultiDict(like_json))
                print("LikeTiezi:",form.data.get('post_id'))
                if form.validate():
                    like_num = Tiezi.like_num_add(form.post_id.data)
                    print('like_num',like_num)
                    return jsonify({
                        'code':200,
                        'msg':'点赞成功',
                        'like_num':like_num
                    })
                else:
                    errors = {field: error[0] for field, error in form.errors.items()}
                    print('errors',errors)
                    return jsonify({'code': 400, 'errors': errors}),400
            elif like_json.get('reply_id'):
                form = PostLikeReplyForm(MultiDict(like_json))
                print("LikeReply:",form.data.get('reply_id'))
                if form.validate():
                    like_num = Reply.like_num_add(form.reply_id.data)
                    return jsonify({
                        'code':200,
                        'msg':'点赞成功',
                        'like_num':like_num
                    })
                else:
                    errors = {field: error[0] for field, error in form.errors.items()}
                    print('errors',errors)
                    return jsonify({'code': 400, 'errors': errors}),400
        except Exception as e:
            print('错误',e)
            return jsonify({
                "code": 500,
                "message": f"获取列表数据失败: {str(e)}",
                "data": None
            })
    else:
        return '点赞'


